import { loadEnv, UserConfig, ConfigEnv } from 'vite';
import { resolve } from 'path';
import { createVitePlugins } from './build/vite/plugin';
import { createProxy } from './build/vite/proxy';
import { wrapperEnv } from './build/utils';
import type { Rule } from 'postcss';
import { OUTPUT_DIR } from './build/constant';

import pkg from './package.json';
import dayjs from 'dayjs';

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
};

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();

  const env = loadEnv(mode, root);

  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env);

  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_DROP_CONSOLE } = viteEnv;

  const isBuild = command === 'build';

  // console.log(env)

  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
      ],
    },
    server: {
      port: VITE_PORT,
      host: true,
      proxy: createProxy(VITE_PROXY),
    },
    build: {
      target: 'es2015',
      outDir: OUTPUT_DIR,
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      minify: 'terser',
      reportCompressedSize: false,
      chunkSizeWarningLimit: 2000,
    },
    define: {
      // setting vue-i18-next
      // Suppress warning
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    css: {
      preprocessorOptions: {
        /*scss: {
          additionalData: '@import "/@/design/index.scss"; @import "/@/design/normalize.scss";',
        },*/
        /*less: {
          additionalData: '@import (reference) "/@/design/index.less"; @import (reference) "/@/design/normalize.less";',
          javascriptEnabled: true,
        },*/
        less: {
          additionalData: '@import "/@/design/index.less";',
          javascriptEnabled: true,
        },
      },
      modules: {
        localsConvention: 'camelCase',
      },
      postcss: {
        plugins: [
          require('postcss-px2vp')({
            viewportWidth(rule: Rule) {
              const file = rule.source?.input.file;
              // 根据文件名动态配置viewport width
              if (file?.includes('vant')) return 375;
              return 750;
            }, // 视窗的宽度，对应的是我们设计稿的宽度，一般是750
            unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数（很多时候无法整除)
            viewportUnit: 'vw', // 指定需要转换成的视窗单位，建议使用vw ; 使用vh是在开发横屏中使用
            selectorBlackList: ['spread-page'], // 指定不转换为视窗单位的类，可以自定义，可以无限添加,建议定义一至两个通用的类名.
            minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位，你也可以设置为你想要的值
            mediaQuery: false, // 允许在媒体查询中转换`px`
          }),
          require('postcss-preset-env')({}),
          require('cssnano')({
            preset: 'default',
          }),
        ],
      },
    },
    plugins: createVitePlugins(viteEnv, isBuild),
    optimizeDeps: {
      include: [],
      exclude: [],
    },
  };
};
